﻿package graphics.raster 
{
	import flash.display.BitmapData;
	import flash.geom.Rectangle;
	/**
	 * ...
	 * @author Nicolas Barradeau
	 */
	public class Bresenham
	{
		
		public function Bresenham() 
		{
			
		}
		
		static protected var _bd:BitmapData;
		static public function set bitmapData( bd:BitmapData ):void
		{
			_bd = bd;
		}
		static public function get bitmapData():BitmapData
		{
			return _bd;
		}
		
		static public function drawRect( rect:Rectangle, color:uint ):void
		{
			
			var x:int = rect.x;
			var y:int = rect.y;
			var w:int = rect.width;
			var h:int = rect.height;
			drawLine( x, y, x + w, y , color);
			drawLine( x+w, y, x + w, y+h, color );
			drawLine( x+w, y+h, x, y+h, color );
			drawLine( x, y+h, x, y, color );
			
		}
		/**
		 * 
		 * @param	x
		 * @param	y
		 * @param	x2
		 * @param	y2
		 * @param	color
		 */
		static public function drawLine( x:int, y:int, x2:int, y2:int, color:uint):void
		{
			if ( _bd == null ) return;
			
			var shortLen:int = y2-y;
			var longLen:int = x2 - x;
			var yLonger:Boolean;
			
			if((shortLen ^ (shortLen >> 31)) - (shortLen >> 31) > (longLen ^ (longLen >> 31)) - (longLen >> 31))
			{
				shortLen ^= longLen;
				longLen ^= shortLen;
				shortLen ^= longLen;
				yLonger = true;
			}
			else
			{
				yLonger = false;
			}
			
			var inc:int = longLen < 0 ? -1 : 1;
			
			var multDiff:Number = longLen == 0 ? shortLen : shortLen / longLen;
			
			if (yLonger) 
			{
				for (var i:int = 0; i != longLen; i += inc) 
				{
					_bd.setPixel32(x + i*multDiff, y+i, color);
				}
			} 
			else 
			{
				for (i = 0; i != longLen; i += inc) 
				{
					_bd.setPixel32(x + i, y + i * multDiff, color);
				}
			}
		}
		/**
		 * 
		 * @param	cx
		 * @param	cy
		 * @param	r
		 * @param	col
		 */
		static public function drawCircle(cx:Number, cy:Number, r:Number, col:uint):void
		{
			if ( _bd == null ) return;
			
			var xp:int  = 0, yp:int= r ;
			var d:int = 3 - (2 * r);
			
			while (xp <= yp)
			{
				
				_bd.setPixel32(cx + xp, cy + yp, col);
				_bd.setPixel32(cx + yp, cy + xp, col);
				_bd.setPixel32(cx - xp, cy + yp, col);
				_bd.setPixel32(cx + yp, cy - xp, col);
				_bd.setPixel32(cx - xp, cy - yp, col);
				_bd.setPixel32(cx - yp, cy - xp, col);
				_bd.setPixel32(cx + xp, cy - yp, col);
				_bd.setPixel32(cx - yp, cy + xp, col);
				
				if (d < 0)
				{
					d += (4*xp)+6;
				}
				else
				{
					d += (4*(xp-yp))+10;
					yp -= 1;
				}
				xp++;
			}
		   
		}
	}

}